/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dnbW.utilW;

/**
 * Encapsulates a stopwatch to measure the performance of some operation
 * @author truongbaquan
 */
public class Stopwatch {
    private long startTime, endTime;
    private boolean running = false;
    private boolean highPrecision = false;

    public boolean isHighPrecision() {
        return highPrecision;
    }

    public void setHighPrecision(boolean highPrecision) {
        this.highPrecision = highPrecision;
    }

    public boolean isRunning() {
        return running;
    }

    public void start() {
        if (!running) {
            running = true;
            startTime = this.highPrecision ? System.nanoTime() :System.currentTimeMillis();
        }
    }

    public void stop() {
        if (running) {
            running = false;
            endTime = this.highPrecision ? System.nanoTime() :System.currentTimeMillis();
        }
    }

    /**
     * Returns the time elapsed between the start and end time. Returns -1 (error) if
     * the stopwatch is running.
     * @return
     */
    public long readTime() {
        if (!running) {
            if (this.highPrecision) {
                return (endTime - startTime) / 1000000;
            } else {
                return endTime - startTime;
            }
        }
        else return -1;
    }
}
